%Use the wage guesses to figure out which varieties are imported and
%exported across which bilateral pairs

ag_import_source_mat = [];
ag_import_share_mat = [];

ag_potential_import_prices_3D = (ag_import_cost_3D.*wage_guess_mat_3D)./ag_qualities_mat_3D;
[ag_consumed_prices_3D, ag_import_sources_3D] = min(ag_potential_import_prices_3D,[],2);
ag_consumed_prices_mat = reshape(ag_consumed_prices_3D,n_varieties_ag,n_countries);
ag_import_source_mat = reshape(ag_import_sources_3D,n_varieties_ag,n_countries);

for cc = 1:length(country)
ag_import_shares.(country{cc}) = accumarray(ag_import_source_mat(:,cc),1,[n_countries 1])./n_varieties_ag;
ag_import_share_mat = [ag_import_share_mat ag_import_shares.(country{cc})];
end

manu_import_source_mat = [];
manu_import_share_mat = [];

manu_potential_import_prices_3D = (manu_import_cost_3D.*wage_guess_mat_3D)./manu_qualities_mat_3D;
[manu_consumed_prices_3D, manu_import_sources_3D] = min(manu_potential_import_prices_3D,[],2);
manu_consumed_prices_mat = reshape(manu_consumed_prices_3D,n_varieties_manu,n_countries);
manu_import_source_mat = reshape(manu_import_sources_3D,n_varieties_manu,n_countries);

for cc = 1:length(country)
manu_import_shares.(country{cc}) = accumarray(manu_import_source_mat(:,cc),1,[n_countries 1])./n_varieties_manu;
manu_import_share_mat = [manu_import_share_mat manu_import_shares.(country{cc})];
end

%Aggregate price indices:
P_a_vec = geomean(ag_consumed_prices_mat);
P_m_vec = geomean(manu_consumed_prices_mat);
P_s_vec = geomean(serv_consumed_prices_mat);

%Once we have the prices, we can calculate the aggregate expenditure shares
%on each good
calculate_consumption_shares_parallel

%Use expenditure shares to calculate total expenditures on each good in
%each country, and then that gives total income from production as well
GDP_vec = L_vec.*wage_guesses;
GDP_mat = repmat(GDP_vec, n_varieties_ag, 1);
ag_expenditure_share_mat = repmat(exp_share_ag_vec, n_varieties_ag, 1);
manu_expenditure_share_mat = repmat(exp_share_manu_vec, n_varieties_ag, 1);
serv_expenditure_share_mat = repmat(exp_share_serv_vec, n_varieties_ag, 1);
ag_income_mat = repmat(exp_share_ag_vec.*GDP_vec, n_countries,1);
manu_income_mat = repmat(exp_share_manu_vec.*GDP_vec, n_countries,1);
serv_income_vec = (exp_share_serv_vec.*GDP_vec);
serv_consumed_prices_mat = wage_guess_mat./serv_qualities_mat;

% Calculate aggregate trade flows
ag_trade_mat = ag_import_share_mat.*ag_income_mat;
manu_trade_mat = manu_import_share_mat.*manu_income_mat;

% Calculate aggregate income
ag_income_vec = sum(ag_import_share_mat.*ag_income_mat,2)';
manu_income_vec = sum(manu_import_share_mat.*manu_income_mat,2)';
total_income_vec = (ag_income_vec+manu_income_vec+serv_income_vec);
